package com.zhiyin.seal.config;

import com.mysql.cj.util.StringUtils;
import com.zhiyin.seal.anno.OperateLog;
import com.zhiyin.seal.constant.SystemConstants;
import com.zhiyin.seal.entity.bo.SystemLogBo;
import com.zhiyin.seal.service.AdminWebService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
public class MyLogAspect {

    @Autowired
    AdminWebService adminWebService;

    //Controller层切点
    @Pointcut("@annotation(com.zhiyin.seal.anno.OperateLog)")
    public void controllerAspect(){

    }

    @Before(value = "controllerAspect()")
    public void doBefore(JoinPoint joinPoint) throws Throwable{
        // 获取请求对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 获取token
        String accessToken = request.getHeader("x-access-token");
        if(StringUtils.isNullOrEmpty(accessToken)){
            return ;
        }
        //调用解密方法
        Claims claims= Jwts.parser()
                .setSigningKey(SystemConstants.WEB_TOKEN_SALT_FIGURE)
                .parseClaimsJws(accessToken)
                .getBody();
        //解密ID
        Integer id=Integer.valueOf(claims.getId());
        //解密用户名
        String username=claims.getSubject();
        if(username != null && id != null){
            /*从切面值入点获取植入点方法*/
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            /*获取切入点方法*/
            Method method = signature.getMethod();
            /*获取方法上的注解值*/
            OperateLog operateLog = method.getAnnotation(OperateLog.class);
            if(operateLog != null){
                SystemLogBo systemLogBo = new SystemLogBo();
                systemLogBo.setOperateUser(username);
                systemLogBo.setOperateType(operateLog.description());
                adminWebService.addSystemLog(systemLogBo);
            }
        }
    }
}
